/**
 * Copyright 2011 Sibaozuan(superskysbz@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package summary.xml.parser;

import java.net.URL;
import java.util.HashMap;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
/**
 * 
 * @author Sibaozuan(superskysbz@gmail.com)
 *
 */
public class XMLParserForSAX extends DefaultHandler{
	private static StringBuffer mBuffer = new StringBuffer();
	private HashMap<String,String> map = new HashMap<String,String>();
	private boolean isParse = false;
	public String name1 = "";
	public String name2 = "";
	public String name3 = "";
	/**
	 * 
	 * @param path
	 */
	public XMLParserForSAX(String path) {
		init(path);
	}
	/**
	 * 
	 * @param path
	 */
	private void init(String path){
		try {
			URL url = new URL(path);
			SAXParserFactory mSaxFactory = SAXParserFactory.newInstance();
			SAXParser mSaxParser = mSaxFactory.newSAXParser();
			XMLReader xmlReader = mSaxParser.getXMLReader();
			xmlReader.setContentHandler(this);
			xmlReader.parse(new InputSource(url.openStream()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	public void startDocument() throws SAXException {
	}
	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes)
			throws SAXException {
		
	}
	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if(qName.equals(name1)){
			map.put(name1, mBuffer.toString());
			mBuffer.delete(0, mBuffer.length());
		}else if(qName.equals(name2)){
			map.put(name2, mBuffer.toString());
			mBuffer.delete(0, mBuffer.length());
		}else if(qName.equals(name3)){
			map.put(name3, mBuffer.toString());
			mBuffer.delete(0, mBuffer.length());
		}
	}
	@Override
	public void endDocument() throws SAXException {
	}
	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		if(isParse){
			mBuffer.append(new String(ch,start,length));
		}
	}
}
